package com.entfrm.biz.it.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.entfrm.biz.it.entity.Repair;
import com.entfrm.biz.it.entity.RepairEmail;
import com.entfrm.biz.it.service.RepairEmailService;
import com.entfrm.biz.it.service.RepairService;
import com.entfrm.biz.system.entity.User;
import com.entfrm.biz.system.service.UserService;
import com.entfrm.biz.system.vo.UserVo;
import com.entfrm.core.base.api.R;
import com.entfrm.core.base.constant.CommonConstants;
import com.entfrm.core.base.util.DateUtil;
import com.entfrm.core.base.util.ExchangeMailUtil;
import com.entfrm.core.security.util.SecurityUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <h3>entfrm</h3>
 * <p>报修单</p>
 *
 * @author : kyc
 * @date : 2020-08-11 15:25
 **/
@Component
@Log4j2
@PropertySource(value = "classpath:config.properties")
public class RepairManager {

    @Autowired
    private RepairService repairService;

    @Autowired
    private UserService userService;

    @Autowired
    private RepairEmailService repairEmailService;

    @Autowired
    private ExchangeMailUtil exchangeMailUtil;

    /**
     * it运维管理员角色code
     */
    @Value("${repair.itOperationManagerCode}")
    private String itOperationManagerCode;

    /**
     * 报修详情
     */
    public Repair getRepairById(Integer id) {
        return repairService.getById(id);
    }

    /**
     * 新增报修单
     */
    public void saveRepair(Repair repair) {
        repair.setStatus(CommonConstants.RepairStatus.WAIT_ASSIGN);
        repairService.save(repair);
        // 获取it运维管理员的邮箱
        List<UserVo> userList = userService.listUserByRoleCode(itOperationManagerCode);
        List<String> recipientTo = new ArrayList<>();
        for (UserVo userVo : userList) {
            recipientTo.add(userVo.getEmail());
        }
        // 标题
        String subject = "新的报修工单待分配!";
        // 发送邮件通知it运维管理员
        sendMail(repair, recipientTo, subject);
    }

    /**
     * 删除报修单
     */
    public R deleteRepair(Integer[] ids) {
        List<Repair> repairList = repairService.listByIds(Arrays.asList(ids));
        for (Repair repair : repairList) {
            if (!repair.getStatus().equals(CommonConstants.RepairStatus.WAIT_ASSIGN)) {
                return R.error("删除失败!");
            }
        }
        return R.ok(repairService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 报修单指派
     */
    public R repairAssign(Repair repair) {
        if (!repair.getStatus().equals(CommonConstants.RepairStatus.WAIT_ASSIGN)) {
            return R.error("状态错误,指派失败!");
        }
        User serviceUser = userService.getById(repair.getServiceId());
        repair.setServiceName(serviceUser.getNickName());
        repair.setServicePhone(serviceUser.getPhone());
        repair.setStatus(CommonConstants.RepairStatus.PROCESSING);
        repair.setAssignTime(new Date());
        // 计算相隔时间
        String datePoor = DateUtil.getDatePoor(repair.getAssignTime(), repair.getCreateTime());
        repair.setAssignDuration(datePoor);
        repairService.updateById(repair);
        // 发送邮件到维修员
        String serviceSubject = "新的报修工单请及时处理";
        List<String> recipientServiceTo = new ArrayList<>();
        recipientServiceTo.add(serviceUser.getEmail());
        sendMail(repair, recipientServiceTo, serviceSubject);
        // 发送邮件到用户
        String userSubject = "报修工单已指派维修员,请稍等!";
        User user = userService.getById(SecurityUtil.getUser().getId());
        List<String> recipientUserTo = new ArrayList<>();
        recipientUserTo.add(user.getEmail());
        sendMail(repair, recipientUserTo, userSubject);
        return R.ok();
    }

    /**
     * 报修单解决回复
     */
    public R repairResolved(Repair repair) {
        if (!repair.getStatus().equals(CommonConstants.RepairStatus.PROCESSING)) {
            return R.error("状态错误,回复失败!");
        }
        repair.setResolveTime(new Date());
        // 计算相隔时间
        String datePoor = DateUtil.getDatePoor(repair.getResolveTime(), repair.getAssignTime());
        repair.setResolveDuration(datePoor);
        repair.setStatus(CommonConstants.RepairStatus.RESOLVED);
        repairService.updateById(repair);
        // 发送邮件到用户
        String subject = "报修工单已解决请查看回复并可进行评价!";
        User user = userService.getById(SecurityUtil.getUser().getId());
        List<String> recipientTo = new ArrayList<>();
        recipientTo.add(user.getEmail());
        // 通知用户
        sendMail(repair,recipientTo,subject);
        return R.ok();
    }

    /**
     * 报修单评价
     */
    public R repairComment(Repair repair) {
        if (!repair.getStatus().equals(CommonConstants.RepairStatus.RESOLVED)) {
            return R.error("状态错误,评价失败!");
        }
        repairService.updateById(repair);
        // 发送邮件到该工单维修员
        String subject = "报修工单收到评价请查看!";
        User serviceUser = userService.getById(repair.getServiceId());
        List<String> recipientTo = new ArrayList<>();
        recipientTo.add(serviceUser.getEmail());
        sendMail(repair,recipientTo,subject);
        return R.ok();
    }



    /**
     * 发送邮件
     *
     * @param repair
     * @return
     */
    private void sendMail(Repair repair, List<String> recipientTo, String subject) {
        // 获取发送邮箱信息
        RepairEmail repairEmail = repairEmailService.getOne(new QueryWrapper<RepairEmail>().lambda().eq(RepairEmail::getIsUse, CommonConstants.Status.YES));
        // 获取工单信息
        String emergency = "";
        if (CommonConstants.RepairEmergency.VERY_URGENT.equals(repair.getEmergency())) {
            emergency = "非常紧急";
        } else if (CommonConstants.RepairEmergency.URGENT.equals(repair.getEmergency())) {
            emergency = "紧急";
        } else {
            emergency = "一般";
        }
        String status = "";
        if (CommonConstants.RepairStatus.WAIT_ASSIGN.equals(repair.getStatus())) {
            status = "待受理";
        } else if (CommonConstants.RepairStatus.PROCESSING.equals(repair.getStatus())) {
            status = "处理中";
        } else {
            status = "已解决";
        }
        StringBuilder builder = new StringBuilder();
        builder.append("报修工单信息：<BR>");
        builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;姓名:" + repair.getName() + "<BR>");
        builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;工号:" + repair.getJobId() + "<BR>");
        builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;联系电话:" + repair.getPhone() + "<BR>");
        builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;报修地址:" + repair.getLocation() + "<BR>");
        if (repair.getServiceName() != null) {
            builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;维修员:" + repair.getServiceName() + "<BR>");
        }
        if (repair.getServicePhone() != null) {
            builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;维修员联系电话:" + repair.getServicePhone() + "<BR>");
        }
        builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;问题描述:" + repair.getProblemInfo() + "<BR>");
        builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;紧急程度:" + emergency + "<BR>");
        builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;状态:" + status + "<BR>");
        if (repair.getComment() != null) {
            builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;评价:" + repair.getComment() + "<BR>");
        }
        if (repair.getReply() != null) {
            builder.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;回复:" + repair.getReply() + "<BR>");
        }
        String message = builder.toString();
        // 发送邮件
        exchangeMailUtil.sendMail(repairEmail.getEmailAccount()
                , repairEmail.getEmailPassword()
                , repairEmail.getEmailHostname()
                , subject, recipientTo, message);
    }
}
